<template>
  <main class="container">
    <template v-if="walletAddress">
      <van-divider>tronLink信息面板</van-divider>
      <van-cell-group>
        <van-cell title="账户">
          <template #label>
            <div class="item">
              <div class="label">钱包地址</div>
              <div class="value">{{ walletAddress }}</div>
            </div>
          </template>
        </van-cell>
        <van-cell title="节点">
          <template #label>
            <div class="item">
              <div class="label">chainId</div>
              <div class="value">{{ tronLinkNodeInfo?.chainId }}</div>
            </div>
            <div class="item">
              <div class="label">eventServer</div>
              <div class="value">{{ tronLinkNodeInfo?.eventServer }}</div>
            </div>
            <div class="item">
              <div class="label">fullNode</div>
              <div class="value">{{ tronLinkNodeInfo?.fullNode }}</div>
            </div>
            <div class="item">
              <div class="label">solidityNode</div>
              <div class="value">{{ tronLinkNodeInfo?.solidityNode }}</div>
            </div>
          </template>
        </van-cell>
      </van-cell-group>
    </template>
    <van-divider>操作面板</van-divider>
    <van-cell-group>
      <van-cell
        title="钱包地址"
        :value="hideStringMiddle(walletAddress, 4, 4, 4)"
        is-link
        @click="connectWallet"
      />
      <van-cell
        title="TRX余额"
        :value="balance"
        is-link
        @click="handleGetBalance"
      />
      <van-cell
        title="USDT代币余额"
        :value="usdtBalance"
        is-link
        @click="handleGetUsdtBalance"
      />
      <van-cell title="USDT代币授权" is-link @click="handleUsdtApprove" />
      <van-cell title="USDT代币转账" is-link @click="handleUsdtTransfer" />
      <van-cell title="TRX转账" is-link @click="handleTrxTransfer" />
      <van-cell title="获取授权额度状态" is-link @click="handleAllowance" />
    </van-cell-group>
  </main>
</template>

<script setup>
import { ref, onUnmounted, onMounted } from "vue";
import { storeToRefs } from "pinia";
import {
  getWalletAddress,
  getBalance,
  getTokenBalance,
  approveTokenTransfer,
  tokenTransfer,
  trxTransfer,
  getAllowance,
} from "@/utils/TronWeb";
import { useTronWebStore } from "@/store";
const { setWalletAddress, setTronLinkNodeInfo } = useTronWebStore();
const { walletAddress, tronLinkNodeInfo } = storeToRefs(useTronWebStore());
import { hideStringMiddle } from "@/utils";
import { handleTronLinkMessageEvent } from "@/utils/TronWeb/subscribe";

import { useUserStore } from "@/store";
const { setToken } = useUserStore();

const connectWallet = async () => {
  try {
    const address = await getWalletAddress();
    console.log("钱包地址: ", address);
    setWalletAddress(address);
    setToken("token-1234567890");
  } catch (err) {
    console.log(err);
  }
};

const balance = ref("");
const handleGetBalance = async () => {
  try {
    const balanceVal = await getBalance(walletAddress.value);
    console.log("余额: ", balanceVal);
    balance.value = balanceVal;
  } catch (err) {
    console.log(err);
  }
};

const usdtBalance = ref("");
const handleGetUsdtBalance = async () => {
  try {
    const balanceVal = await getTokenBalance({
      walletAddress: walletAddress.value,
    });
    console.log("余额: ", balanceVal);
    usdtBalance.value = balanceVal;
  } catch (err) {
    console.log(err);
  }
};

const handleUsdtApprove = async () => {
  approveTokenTransfer({
    walletAddress: walletAddress.value,
    amount: 1000000000,
  })
    .then((res) => {
      if (res) {
        showSuccessToast("授权成功");
      } else {
        showFailToast("授权失败");
      }
    })
    .catch((error) => {
      showFailToast("授权失败");
    });
};

const handleUsdtTransfer = async () => {
  tokenTransfer({
    amount: 1,
  })
    .then((res) => {
      console.log(res);
      // if (res) {
      //   showSuccessToast("交易成功");
      // } else {
      //   showFailToast("交易失败");
      // }
    })
    .catch((error) => {
      showFailToast("交易失败");
    });
};

const handleTrxTransfer = async () => {
  trxTransfer({
    amount: 1,
  })
    .then((res) => {
      // if (res) {
      //   showSuccessToast("交易成功");
      // } else {
      //   showFailToast("交易失败");
      // }
    })
    .catch((error) => {
      showFailToast("交易失败");
    });
};

const handleAllowance = async () => {
  getAllowance({
    walletAddress: walletAddress.value,
  })
    .then((res) => {
      if (res) {
        showSuccessToast("存在额度");
      } else {
        showFailToast("额度不足");
      }
    })
    .catch((error) => {
      showFailToast("交易失败");
    });
};

onUnmounted(() => {
  handleTronLinkMessageEvent("remove");
});

onMounted(() => {
  handleTronLinkMessageEvent("add", (data) => {
    if (data.type == "disconnect") {
      showFailToast("tronLink已断开连接");
      setWalletAddress(undefined);
      setTronLinkNodeInfo(null);
    }
    if (data.type == "accountsChanged") {
      showFailToast("tronLink账户已切换");
      setWalletAddress(data.address);
    }
    if (data.type == "setNode") {
      showFailToast("tronLink已切换节点");
      setTronLinkNodeInfo({
        chainId: data.node.chainId,
        eventServer: data.node.eventServer,
        fullNode: data.node.fullNode,
        solidityNode: data.node.solidityNode,
      });
    }
    if (data.type == "acceptWeb") {
      showSuccessToast("tronLink已连接");
      setTronLinkNodeInfo({
        chainId: data.node.chainId,
        eventServer: data.node.eventServer,
        fullNode: data.node.fullNode,
        solidityNode: data.node.solidityNode,
      });
    }
  });
});
</script>
<style lang="scss" scoped>
:deep(.van-cell__title) {
  width: 100%;
}
.item {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 5px 0;
  font-size: 12px;
  .label {
    color: #999;
  }
  .value {
    color: #333;
  }
}
</style>
